#!/usr/bin/env python
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import traceback
from time import sleep
import rocksdb
from os.path import join,dirname,abspath
from requests import Session
from hashlib import blake2b
from json import loads

ROOT = dirname(abspath(__file__))

class Cache:
    def __init__(self, db):
        self.session = Session()
        self._db = rocksdb.DB(
            join(ROOT,'cache',db),
            rocksdb.Options(create_if_missing=True)
        )

    def get(self, url, headers={}, verify=lambda x:True):
        cache = self._db
        key = blake2b(url.encode('utf-8','ignore')).digest()
        r = cache.get(key)
        if r:
            # print('cached')
            r = loads(r)
            return r
        # headers.update(proxy_header())
        while 1:
            try:
                r = self.session.get(
                    url,
                    timeout=60,
                    verify=False,
                    # proxies=dict(http=PROXY, https=PROXY),
                    headers=headers
                )
                j = r.json()
                if verify(j):
                    cache.put(
                        key,
                        r.content
                    )
                return j
            except Exception:
                traceback.print_exc()
